package fudan.se.project.service.infrastructure.entity.conference.post;

import fudan.se.project.domain.User;
import fudan.se.project.domain.conference.post.Rebuttal;
import fudan.se.project.domain.conference.production.ReviewInfo;
import fudan.se.project.domain.conference.production.ReviewInfo.ReviewInfoState;
import fudan.se.project.repository.entity.conference.post.RebuttalRepository;
import fudan.se.project.service.infrastructure.base.IEntityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Set;

@Slf4j
@Service
public class RebuttalService implements IEntityService<Rebuttal> {
    private final RebuttalRepository rebuttalRepository;

    @Autowired
    public RebuttalService(RebuttalRepository rebuttalRepository) {
        this.rebuttalRepository = rebuttalRepository;
    }

    public Rebuttal findByPaperId(long paperId) {
        return rebuttalRepository.findByPostPaperId(paperId);
    }

    public List<Rebuttal> findRebuttalsForAuthor(long conferenceId, User author) {
        return rebuttalRepository.
                findRebuttalsByConferenceIdAndAuthor(conferenceId, author);
    }

    public List<Rebuttal> findRebuttalsForReviewer(long conferenceId, User reviewer, boolean confirmed) {
        int version = confirmed ? 2 : 1;
        return rebuttalRepository.
                findRebuttalsByConferenceIdAndReviewerAndVersion(conferenceId, reviewer, version);
    }

    @Override
    public Rebuttal findById(long id) {
        return rebuttalRepository.findById(id);
    }

    @Override
    public Rebuttal save(Rebuttal rebuttal) {
        return rebuttalRepository.save(rebuttal);
    }

    @Override
    public Iterable<Rebuttal> saveAll(Collection<Rebuttal> rebuttals) {
        return rebuttalRepository.saveAll(rebuttals);
    }

    public boolean isRebuttable(Set<ReviewInfo> reviewInfos) {
        for (ReviewInfo reviewInfo : reviewInfos) {
            if (reviewInfo.getReviewInfoState().equals(ReviewInfoState.WEAK_REJECT) ||
                    reviewInfo.getReviewInfoState().equals(ReviewInfoState.REJECT))
                return true;
        }
        return false;

    }
}
